package com.piece.module.spider.service;

import com.piece.core.jpa.repository.BaseService;
import com.piece.module.spider.expression.ExpressionGlobalVariables;
import com.piece.module.spider.model.Variable;
import com.piece.module.spider.response.VariableRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class VariableService extends BaseService<Variable, Long> {

    @Autowired
    private VariableRepository variableRepository;

    /**
     * 初始化/重置自定义函数
     */
    @PostConstruct
    public void initRepository() {
        super.setRepository(variableRepository);
        resetGlobalVariables();
    }

    private void resetGlobalVariables(){
        Map<String, String> variables = findAllWithOutStatus().stream().collect(Collectors.toMap(Variable::getName, Variable::getValue));
        ExpressionGlobalVariables.reset(variables);
    }

    @Override
    public Variable insert(Variable variable) throws Exception {
        return insertOrUpdate(variable);
    }

    @Override
    public Variable insertOrUpdate(Variable variable) throws Exception {
        variable = super.insertOrUpdate(variable);
        this.resetGlobalVariables();
        return variable;
    }

    @Override
    public void delete(Serializable id) throws Exception {
        super.delete(id);
        this.resetGlobalVariables();
    }
}
